//
//  ActionView.m
//  MyWallet
//
//  Created by 小肥羊 on 15/7/17.
//  Copyright (c) 2015年 小肥羊. All rights reserved.
//

#import "ActionView.h"

@implementation ActionView

#pragma mark - 单例
+ (ActionView *)sharedActionView
{
    static ActionView *actionView = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        CGRect rect = [[UIScreen mainScreen] bounds];
        actionView = [[ActionView alloc] initWithFrame:rect];
        [[NSNotificationCenter defaultCenter] addObserver:actionView selector:@selector(closeView:) name:CLOESNOTICE object:nil];
    });
    return actionView;
}

#pragma mark - 初始化
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _views = [NSMutableArray array];    //先设置，否则弹出动画找不到views,无法播放动画
        
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        _tapGesture.delegate = self;
        [self addGestureRecognizer:_tapGesture];
    }
    return self;
}

#pragma mark - 点击背景触发
- (void)tapAction:(UITapGestureRecognizer *)tapGesture{
    CGPoint touchPoint = [tapGesture locationInView:self];
    UIView *view = self.views.lastObject;
    if (!CGRectContainsPoint(view.frame, touchPoint)) {
        [[ActionView sharedActionView] dismissMenu:view Animated:YES];
        [self.views removeObject:view];
    }
}

#pragma mark - 动画设置
- (CAAnimation *)dimingAnimation
{
    if (_dimingAnimation == nil) {
        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
        opacityAnimation.fromValue = (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor];
        opacityAnimation.toValue = (id)[[UIColor colorWithWhite:0.0 alpha:0.4] CGColor];
        [opacityAnimation setRemovedOnCompletion:NO];
        [opacityAnimation setFillMode:kCAFillModeBoth];
        _dimingAnimation = opacityAnimation;
    }
    return _dimingAnimation;
}

- (CAAnimation *)lightingAnimation
{
    if (_lightingAnimation == nil ) {
        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
        opacityAnimation.fromValue = (id)[[UIColor colorWithWhite:0.0 alpha:0.4] CGColor];
        opacityAnimation.toValue = (id)[[UIColor colorWithWhite:0.0 alpha:0.0] CGColor];
        [opacityAnimation setRemovedOnCompletion:NO];
        [opacityAnimation setFillMode:kCAFillModeBoth];
        _lightingAnimation = opacityAnimation;
    }
    return _lightingAnimation;
}

- (CAAnimation *)showViewAnimation
{
    if (_showViewAnimation == nil) {
        CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
        //        CATransform3D t = CATransform3DIdentity;
        //        t.m34 = 1 / -500.0f;
        //        CATransform3D from = CATransform3DRotate(t, -30.0f * M_PI / 180.0f, 1, 0, 0);
        //        CATransform3D to = CATransform3DIdentity;
        //        [rotateAnimation setFromValue:[NSValue valueWithCATransform3D:from]];
        //        [rotateAnimation setToValue:[NSValue valueWithCATransform3D:to]];
        
        CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [scaleAnimation setFromValue:@0.9];
        [scaleAnimation setToValue:@1.0];
        
        CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        //        [positionAnimation setFromValue:[NSNumber numberWithFloat:50.0]];
        //        [positionAnimation setToValue:[NSNumber numberWithFloat:0.0]];
        
        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        [opacityAnimation setFromValue:@0.0];
        [opacityAnimation setToValue:@1.0];
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        [group setAnimations:@[rotateAnimation, scaleAnimation, opacityAnimation, positionAnimation]];
        [group setRemovedOnCompletion:NO];
        [group setFillMode:kCAFillModeBoth];
        _showViewAnimation = group;
    }
    return _showViewAnimation;
}

- (CAAnimation *)dismissViewAnimation
{
    if (_dismissViewAnimation == nil) {
        CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
        //        CATransform3D t = CATransform3DIdentity;
        //        t.m34 = 1 / -500.0f;
        //        CATransform3D from = CATransform3DIdentity;
        //        CATransform3D to = CATransform3DRotate(t, -30.0f * M_PI / 180.0f, 1, 0, 0);
        //        [rotateAnimation setFromValue:[NSValue valueWithCATransform3D:from]];
        //        [rotateAnimation setToValue:[NSValue valueWithCATransform3D:to]];
        
        CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [scaleAnimation setFromValue:@1.0];
        [scaleAnimation setToValue:@0.9];
        
        CABasicAnimation *positionAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        //        [positionAnimation setFromValue:[NSNumber numberWithFloat:0.0]];
        //        [positionAnimation setToValue:[NSNumber numberWithFloat:50.0]];
        
        CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
        [opacityAnimation setFromValue:@1.0];
        [opacityAnimation setToValue:@0.0];
        
        CAAnimationGroup *group = [CAAnimationGroup animation];
        [group setAnimations:@[rotateAnimation, scaleAnimation, opacityAnimation, positionAnimation]];
        [group setRemovedOnCompletion:NO];
        [group setFillMode:kCAFillModeBoth];
        _dismissViewAnimation = group;
    }
    return _dismissViewAnimation;
}


#pragma mark - 显示视图
+ (void)showView:(UIView *)view;
{
    [[ActionView sharedActionView] setView:view animation:YES direction:PopViewDirectionStyleCenter];
}

+ (void)showView:(UIView *)view direction:(PopViewDirectionStyle)directionStyle
{
    [[ActionView sharedActionView] setView:view animation:YES direction:directionStyle];
}

#pragma mark - 显示视图并播放动画
- (void)setView:(UIView *)view animation:(BOOL)animated{
    [self setView:view animation:animated direction:PopViewDirectionStyleCenter];
}

- (void)setView:(UIView *)view animation:(BOOL)animated direction:(PopViewDirectionStyle)directionStyle{
    if (![self superview]) {
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        [window addSubview:self];
    }
    
    [self.views makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.views addObject:view];
    
    [self addSubview:view];
    [view layoutIfNeeded];
    view.frame = [self rectWithView:view directionStyle:directionStyle];
    
    //如果是第一个弹出的视图,并且设置了动画，弹出时播放动画
    if (animated && self.views.count == 1) {
        [CATransaction begin];
        [CATransaction setAnimationDuration:0.2];
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
        [self.layer addAnimation:self.dimingAnimation forKey:@"diming"];
        [view.layer addAnimation:self.showViewAnimation forKey:@"showView"];
        [CATransaction commit];
    }
}

- (void)dismissMenu:(UIView *)view Animated:(BOOL)animated
{
    if ([self superview]) {
        [self.views removeObject:view];
        if (animated && self.views.count == 0) {
            [CATransaction begin];
            [CATransaction setAnimationDuration:0.2];
            [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
            [CATransaction setCompletionBlock:^{
                [self removeFromSuperview];
                [view removeFromSuperview];
            }];
            [self.layer addAnimation:self.lightingAnimation forKey:@"lighting"];
            [view.layer addAnimation:self.dismissViewAnimation forKey:@"dismissView"];
            [CATransaction commit];
        }else{
            [view removeFromSuperview];
            
            UIView *topView = self.views.lastObject;
            [self addSubview:topView];
            [topView layoutIfNeeded];
        }
    }
}

#pragma mark - 根据方向计算显示位置
- (CGRect)rectWithView:(UIView *)view directionStyle:(PopViewDirectionStyle)directionStyle
{
    CGPoint point;
    float shiftingX = (self.bounds.size.width - view.bounds.size.width)/2;
    switch (directionStyle) {
        case PopViewDirectionStyleCenter:
            point = CGPointMake(shiftingX, (self.bounds.size.height - view.bounds.size.height)/2);
            break;
        case PopViewDirectionStyleUp:
            point = CGPointMake(shiftingX, 0);
            break;
        case PopViewDirectionStyleDown:
            point = CGPointMake(shiftingX, self.bounds.size.height - view.bounds.size.height);
            break;
        case PopViewDirectionStyleDIY:
            point = CGPointMake(view.frame.origin.x, view.frame.origin.y);
            break;
        default:
            point = CGPointMake(view.frame.origin.x, view.frame.origin.y);
            break;
    }
    return (CGRect){point, view.bounds.size};
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */


- (void) closeView:(NSNotification*) notification
{
    UIView *obj = [notification object];//获取到传递的对象
    [[ActionView sharedActionView] dismissMenu:obj Animated:YES];
}
@end
